package chaoyue.study.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 工具Controller
 */
@RestController
@RequestMapping("test")
public class ShowInfoController {

    /**
     * 打印hello
     */
    @GetMapping("showHello")
    public String showHello() {
        return "hello";
    }

    /**
     * 打印Header
     */
    @GetMapping("showHeader")
    public Map<String, Object> showHeader(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            resultMap.put(key, request.getHeader(key));
        }
        return resultMap;
    }

    /**
     * 打印参数
     */
    @GetMapping("showParam")
    public Map<String, Object> showParam(HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((k, v) -> {
            if (v != null) {
                if (v.length == 1) {
                    resultMap.put(k, v[0]);
                } else {
                    resultMap.put(k, Arrays.asList(v));
                }
            }
        });
        return resultMap;
    }
}
